package com.wrbug.mmkw.compile

import com.squareup.javapoet.ClassName
import com.wrbug.mmkw.annotation.KwData
import com.wrbug.mmkw.annotation.KwInterface
import com.wrbug.mmkw.compile.generator.FinderGenerator
import com.wrbug.mmkw.compile.generator.ImplGenerator
import java.util.HashSet
import javax.annotation.processing.*
import javax.lang.model.SourceVersion
import javax.lang.model.element.TypeElement
import javax.tools.Diagnostic

/**
 *   MmkwProcessor.java
 *   author: wrbug
 *   date: 2019-09-23 17:47
 *
 */


class MmkwProcessor : AbstractProcessor() {

    private lateinit var mFiler: Filer

    companion object {
        lateinit var mMessager: Messager
    }

    override fun init(p0: ProcessingEnvironment) {
        super.init(p0)
        mMessager = processingEnv.messager
        mFiler = processingEnv.filer
    }

    override fun getSupportedAnnotationTypes(): MutableSet<String> {
        val supportAnnotations = HashSet<String>()
        supportAnnotations.add(KwInterface::class.java.canonicalName)
        supportAnnotations.add(KwData::class.java.canonicalName)
        return supportAnnotations
    }

    override fun getSupportedSourceVersion(): SourceVersion = SourceVersion.latestSupported()

    override fun process(p0: MutableSet<out TypeElement>?, roundEnvironment: RoundEnvironment?): Boolean {

        roundEnvironment?.let {
            processKwInterface(p0, it)
            processKwData(p0, it)
        }
        return false
    }

    private fun processKwData(p0: MutableSet<out TypeElement>?, roundEnvironment: RoundEnvironment) {
        val set = roundEnvironment.getElementsAnnotatedWith(KwData::class.java)
//        loge("processKwData" + set)

    }

    private fun processKwInterface(p0: MutableSet<out TypeElement>?, roundEnvironment: RoundEnvironment) {
        val set = roundEnvironment.getElementsAnnotatedWith(KwInterface::class.java) ?: return
        val generator = ImplGenerator(mFiler)
        val arr = ArrayList<ClassName>()
        set.filter { it is TypeElement }.forEach {
            generator.setElement(it as TypeElement)
            generator.generate()
            arr.add(generator.className)
        }
        FinderGenerator(mFiler,arr).generate()
    }
}


fun log(msg: Any?) {
    MmkwProcessor.mMessager.printMessage(Diagnostic.Kind.NOTE, msg?.toString())
}

fun loge(msg: Any?) {
    MmkwProcessor.mMessager.printMessage(Diagnostic.Kind.ERROR, msg?.toString())
}